package com.speedcar.base.util;

import com.speedcar.base.exception.ErrorCode;
import com.speedcar.base.exception.SpeedCarCheckException;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

public class DateUtil {

    private static final String DATE_FORMAT = "yyyy-MM-dd";

    /**
     * 字符串转LocalDate
     *
     * @param dateString 日期字符串
     * @return LocalDate
     */
    public static LocalDate stringToLocalDate(String dateString) {
        if (dateString == null) {
            return null;
        }
        if (dateString.length() == 7) {
            dateString = dateString + "-01";
        }
        if (dateString.length() != 10) {
            throw new SpeedCarCheckException(ErrorCode.PARAM_ERROR, "日期格式错误:" + dateString);
        }
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(DATE_FORMAT);
        return LocalDate.parse(dateString, formatter);
    }

    /**
     * LocalDate转字符串
     *
     * @param localDate LocalDate
     * @return 日期字符串
     */
    public static String localDateToString(LocalDate localDate) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(DATE_FORMAT);
        return localDate.format(formatter);
    }

}
